//
//  WmcHomeNoticeView.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/4/15.
//

import UIKit

class WmcHomeNoticeView: WmcBaseView {
    var currentNoticeView: UIView?

    var noticeViewMap: [String: UIView] = [:]

    /// 开始布局的回调
    var noticeLayoutBlock: YPBlock.OneParam<[UIView]>?
    /// 需要忽略点击事件的区域
    var ignoreViews: [UIView] = []

    override func makeUI() {
        backgroundColor = .clear
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        var hitViews: [UIView] = []
        noticeViewMap.values.forEach { view in
            hitViews.append(view)
        }
        noticeLayoutBlock?(hitViews)
    }

    /// 重写
    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        for view in ignoreViews {
            let frame = view.convert(view.bounds, to: self)
            if frame.contains(point) {
                return nil
            }
        }
        return super.hitTest(point, with: event)
    }

    func addNoticeView(_ view: UIView, key: String) {
        currentNoticeView?.removeFromSuperview()
        currentNoticeView = view
        addSubview(view)
        view.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
        }
        noticeViewMap[key] = view
        Wmc_ViewSpringAnimation(view, isShow: true)
    }

    func removeNoticeView(_ key: String) {
        if let noticeView = noticeViewMap[key] {
            Wmc_ViewSpringAnimation(noticeView, isShow: false, completion: { [weak noticeView] in
                guard let weakNoticeView = noticeView else { return }
                weakNoticeView.removeFromSuperview()
            })
            noticeViewMap.removeValue(forKey: key)
        }
    }
}
